package com.xxxx.server.config.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {
    public  static  final  String CLAIM_KEY_USERNAME="sub";
    public  static  final  String CLAIM_KEY_CREATED="created";
    @Value("${jwt.secret}")
    private  String secret;
    @Value("${jwt.expiration}")
    private  Long expiration;

    public  String  generateToken(UserDetails userDetails)
    {
        Map<String,Object> claim=new HashMap<>();
        claim.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claim.put(CLAIM_KEY_CREATED, new Date());
        return  generateToken(claim);
    }
    private   String  generateToken(Map<String,Object> claim)
    {
        return Jwts.builder()
                .setClaims(claim)
                .setExpiration(generateExpirationData())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();

    }

   private Date generateExpirationData(){
        return  new Date(System.currentTimeMillis()+expiration*1000);
   }

   public String getUserNameFromToken( String token)
   {
       String username;
       Claims claims=getClaimFromToken(token );
       username=claims.getSubject();
    return username;
   }

    private Claims getClaimFromToken(String token) {
        return  Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    public Boolean volidateToken(String token, UserDetails userDetails)
    {
        String username=getUserNameFromToken(token);
        return username.equals(userDetails.getUsername())&&!isTokenExpiration(token);
    }

    private boolean isTokenExpiration(String token) {
       Date expirated=  getExpiratedFromtoken(token);
       return expirated.before(new Date());
    }

    private Date getExpiratedFromtoken(String token) {
        Claims claims=getClaimFromToken(token);
        return claims.getExpiration();
    }
    public Boolean canRefreshToken(String token)
    {
        return !isTokenExpiration(token);
    }
     public    String refreshToken(String token)
{
    Claims claims=getClaimFromToken(token);
    claims.put(CLAIM_KEY_CREATED, new Date());
    return generateToken(claims);
}
}
